using System;
using System.Collections.Generic;
using System.Linq;

namespace LeanUi.ImageBundle
{
    public class CssBuilder
    {
        public string GenerateCss(IList<ImageRect> imageRects) 
        {
            int mainHeight = GetMostUsed(imageRects, i => i.Height);
            int mainWidth = GetMostUsed(imageRects, i => i.Width);

            string rules = GetMainCssSpriteRule( mainWidth, mainHeight ) +
                           imageRects.Join( x=> GenerateCssRule(x, mainWidth, mainHeight), Environment.NewLine);

            return rules;
        }
   
        private int GetMostUsed<T>(IEnumerable<T> imageRects, Func<T, int> selector)
        {
            var valuesGrouped = imageRects.Select(selector).ToLookup(x => x);
            int maxCountSofar = 0;
            int mostUsedValueSoFar = 0;
            foreach (var val in valuesGrouped) {
                if (maxCountSofar < val.Count()) {
                    maxCountSofar = val.Count();
                    mostUsedValueSoFar = val.First();
                }
            }
            return mostUsedValueSoFar;
        }

        private string GetMainCssSpriteRule(int mainWidth, int mainHeight)
        {
           return String.Format( CodeGenerationTemplates.CssMainSpriteRule_2, mainWidth, mainHeight);
        }
    
        private string GenerateCssRule(ImageRect i, int mainWidth, int mainHeight)
        {
            string widthString = (i.Width != mainWidth) ? string.Format(CodeGenerationTemplates.CssWidth_1, i.Width) : "";
            string heightString = (i.Height != mainHeight) ? string.Format(CodeGenerationTemplates.CssHeight_1, i.Height) : "";

            return i.IsDisabledSprite() 
                ? String.Format( 
                    CodeGenerationTemplates.CssDisabledSpriteRule_4,
                    NamingHelper.GetNondisabledSpriteClassFor(i.Name), -i.Left, -i.Top, widthString, heightString)
                : String.Format( 
                    CodeGenerationTemplates.CssSpriteRule_4, 
                    NamingHelper.GetSpriteClassFor(i.Name), -i.Left, -i.Top, widthString, heightString);
        }

    }
}